package com.fusetech.os.core.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.fusetech.os.core.annotation.metafill.MetaObjectFill;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Date;

/**
 * Mybatis填充器
 * @author Luzhengning
 * @description
 * @date 2023年03月22日 11:34
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 添加数据时填充
     * @author luzhengning
     * @date 2023/3/22 11:37
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "delFlag", Integer.class, 0); //新增数据时，默认为0  采用了注入器
        //this.strictInsertFill(metaObject, "createBy", String.class, getCurrentUserId());
        this.strictInsertFill(metaObject, "createDate", Date.class, new Date());
        //this.strictInsertFill(metaObject, "updateBy", String.class, getCurrentUserId());
        this.strictInsertFill(metaObject, "updateDate", Date.class, new Date());

        //自定义字段填充
        Class<?> aClass = metaObject.getOriginalObject().getClass();
        for (Field field : aClass.getDeclaredFields()) {
            MetaObjectFill annotation = field.getAnnotation(MetaObjectFill.class);
            if(annotation==null){
              continue;
            }
            //组织机构字段填充
            /*if(annotation.metaType()== FillMetaType.OrgId){
                String value=getCurrentUserOrgId();
                this.strictInsertFill(metaObject, field.getName(), String.class, value);
            }*/
        }

    }

    /**
     * 修改时填充
     *
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        /*this.strictUpdateFill(metaObject, "updateBy", String.class, getCurrentUserId());
        this.strictUpdateFill(metaObject, "updateDate", Date.class, new Date());*/
    }
    /**
     * 获取当前登录用的ID
     *
     */
    /*private String getCurrentUserId(){
        try {
            return SecurityUtils.getCurrentUserId();
        } catch (AuthenicException e) {
            return null;
        }catch (Exception e){
            return null;
        }
    }*/

    /**
     * 获取当前用户组织机构ID
     * @Date 2023/6/8 16:34
     * @Author luzhengning
     **/
    /*private String getCurrentUserOrgId(){
        try {
            return SecurityUtils.getCurrentOrg().get(0).getId();
        } catch (AuthenicException e) {
            return null;
        }catch (Exception e){
            return null;
        }
    }*/

}
